package hust.hbhmzy.udpchat;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import javax.security.auth.login.LoginException;

//主页面
public class MainActivity extends Activity {

	static final String LOG_TAG = "UDPchat_Main";
	private static final int LISTENER_PORT = 50003;
	private static final int BUF_SIZE = 1024;
	private ContactManager contactManager;
	private String displayName;
	private InetAddress ip;
	private boolean STARTED = false;
	private boolean IN_CALL = false;
	private boolean LISTEN = false;

	public final static String EXTRA_CONTACT = "hust.hbhmzy.udpchat.CONTACT";
	public final static String EXTRA_IP = "hust.hbhmzy.udpchat.IP";
	public final static String EXTRA_DISPLAYNAME = "hust.hbhmzy.udpchat.DISPLAYNAME";

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Intent intent1 = getIntent();
		//获取从登陆页面传递过来的name显示在textview 上
		displayName = intent1.getStringExtra("displayname");
		ip = (InetAddress) intent1.getSerializableExtra("IP");
		Log.i(LOG_TAG, "UDPChat started");
		init();
	}

	private void init() {
		TextView textView = findViewById(R.id.editTextDisplayName);
		textView.setText(displayName);
		ScrollView scrollView = findViewById(R.id.scrollView);
		scrollView.setVisibility(View.VISIBLE);

		contactManager = new ContactManager(displayName, ip);
		startCallListener();//在50003端口开启监听是否收到 有来电。


		// 更新好友列表按钮
		// 更新通过cantactManager获取的好友
		final Button btnUpdate =  findViewById(R.id.buttonUpdate);
		btnUpdate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				updateContactList();
			}
		});

		//通知好友 由于登录先后问题，可能后登录的暂时没接收到先登录的用户所发的包，等待几秒后可以获取到对方重新发送的包，也可以让先登录的用户按此按钮再次发送，可以立即显示。
		final Button btnrebc =  findViewById(R.id.buttonrebroadcast);
		btnrebc.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				contactManager.rebroad();

			}
		});

		// 拨打  按钮
		// 选择一个好友 进行拨打
		final Button btnCall = findViewById(R.id.buttonCall);
		btnCall.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				RadioGroup radioGroup =  findViewById(R.id.contactList);
				int selectedButton = radioGroup.getCheckedRadioButtonId();
				if(selectedButton == -1) {
					// 如果没有选取好友，弹出一个AlertDialog
					Log.w(LOG_TAG, "Warning: no contact selected");
					final AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
					alert.setTitle("提示");
					alert.setMessage("您得先选一个好友拨打呦");
					alert.setButton(-1, "OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {

							alert.dismiss();
						}
					});
					alert.show();
					return;
				}
				//获取这个cotact的ip与name
				RadioButton radioButton =  findViewById(selectedButton);
				String contact = radioButton.getText().toString();
				InetAddress ip = contactManager.getContacts().get(contact);
				IN_CALL = true;//将自身状态改为true  拨打

				// 通过Intent跳转到MakeCallActivity，同时将这些信息传递过去
				Intent intent = new Intent(MainActivity.this, MakeCallActivity.class);
				intent.putExtra(EXTRA_CONTACT, contact);
				String address = ip.toString();
				address = address.substring(1, address.length());
				intent.putExtra(EXTRA_IP, address);
				intent.putExtra(EXTRA_DISPLAYNAME, displayName);
				startActivity(intent);
			}
		});
	}


	//// 更新通过cantactManager获取的好友的方法
	private void updateContactList() {
		// 创建一个新的HashMap引用指向contactManager里的contact
		HashMap<String, InetAddress> contacts = contactManager.getContacts();
		Log.e("contacts_number", String.valueOf(contacts.size()));

		RadioGroup radioGroup =  findViewById(R.id.contactList);
		radioGroup.removeAllViews();

		for(String name : contacts.keySet()) {
			RadioButton radioButton = new RadioButton(getBaseContext());
			radioButton.setText(name);
			radioButton.setTextColor(Color.BLACK);
			radioGroup.addView(radioButton);
		}

		radioGroup.clearCheck();
	}



	//开启监听线程，接收是否有 来电的消息“CALL”
	private void startCallListener() {
		// Creates the listener thread
		LISTEN = true;
		Thread listener = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					// Set up the socket and packet to receive
					Log.i(LOG_TAG, "Incoming call listener started");
					DatagramSocket socket = new DatagramSocket(LISTENER_PORT);
					socket.setSoTimeout(1000);
					byte[] buffer = new byte[BUF_SIZE];
					DatagramPacket packet = new DatagramPacket(buffer, BUF_SIZE);
					while(LISTEN) {
						// Listen for incoming call requests
						try {
							Log.i(LOG_TAG, "Listening for incoming calls");
							socket.receive(packet);
							String data = new String(buffer, 0, packet.getLength());
							Log.i(LOG_TAG, "Packet received from "+ packet.getAddress() +" with contents: " + data);
							String action = data.substring(0, 4);
							if(action.equals("CAL:")) {
								// 收到电话请求. 开启ReceiveCallActivity
								String address = packet.getAddress().toString();
								String name = data.substring(4, data.length());
								Intent intent = new Intent(MainActivity.this, ReceiveCallActivity.class);
								intent.putExtra(EXTRA_CONTACT, name);
								intent.putExtra(EXTRA_IP, address.substring(1, address.length()));
								IN_CALL = true;
								//LISTEN = false;
								//stopCallListener();
								startActivity(intent);
							}
							else {
								// Received an invalid request
								Log.w(LOG_TAG, packet.getAddress() + " sent invalid message: " + data);
							}
						}
						catch(Exception e) {}
					}
					Log.i(LOG_TAG, "Call Listener ending");
					socket.disconnect();
					socket.close();
				}
				catch(SocketException e) {

					Log.e(LOG_TAG, "SocketException in listener " + e);
				}
			}
		});
		listener.start();
	}

	private void stopCallListener() {
		// 结束监听线程
		LISTEN = false;
	}

	@Override
	public void onPause() {

		super.onPause();
		if(STARTED) {

			contactManager.bye(displayName);
			contactManager.stopBroadcasting();
			contactManager.stopListening();
			//STARTED = false;
		}
		stopCallListener();
		Log.i(LOG_TAG, "App paused!");
	}

	@Override
	public void onStop() {

		super.onStop();
		Log.i(LOG_TAG, "App stopped!");
		stopCallListener();
		if(!IN_CALL) {
			finish();
		}
	}

	@Override
	public void onRestart() {
		super.onRestart();
		//当回到MainActivity的时候，重新开启监听，并发送播报自身ip消息
		Log.e(LOG_TAG, "App restarted!");
		IN_CALL = false;
		STARTED = true;
//		contactManager = new ContactManager(displayName, ip);
		contactManager.restart();
		startCallListener();
	}
}